//
//  LGInspectionReportController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/1.
//  报告中心 -- 检验检查报告

#import "LGInspectionReportController.h"
//报告详情
#import "LGInspectReportDetailController.h"
//新增检验检查报告
#import "LGAddInspectReportController.h"
//报告详情
#import "LGReportDetailLRController.h"
#import "LGReportDetailCT01Controller.h"
#import "LGReportDetailCT02Controller.h"

#import "LGReportCenterHeaderView.h"
#import "LGInspectionReportCell.h"
#import "LGCheckPhotoTool.h"
#import "LGPickerView.h"

@interface LGInspectionReportController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UIView *topLine;
/**   */
@property (nonatomic , strong)UIButton *typeButton;
/**   */
@property (nonatomic , strong)UIButton *yearButton;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *addButton;
/**   */
@property (nonatomic , copy)NSString *type;
/**   */
@property (nonatomic , copy)NSString *typeStr;
/**   */
@property (nonatomic , strong)NSArray *typeArray;
/**   */
@property (nonatomic , strong)NSArray *pickerArray;
/**   */
@property (nonatomic , copy)NSString *year;
/**   */
@property (nonatomic , strong)NSMutableArray *yearArray;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , assign)CGPoint checkPoint;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
@end

@implementation LGInspectionReportController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.year = @"";
    self.type = @"";
    self.yearArray = [NSMutableArray array];
    [self.yearArray addObject:@"全部时间"];
    NSInteger currentYear = [[self.formatter stringFromDate:[NSDate date]] integerValue];
    for (NSInteger i=currentYear; i>=2015; i--) {
        [self.yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
//    [self.view addSubview:self.topLine];
    [self.view addSubview:self.typeButton];
    [self.view addSubview:self.yearButton];
    [self.view addSubview:self.tableView];
//    [self.view addSubview:self.addButton];
    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
    self.emptyView.backgroundColor = [UIColor clearColor];
    [self.emptyView stopBufferAction];
    self.typeStr = self.typeButton.titleLabel.text;
    
}

//模块被选中
-(void)viewWillAppearAction{
    [self requestData];
}

-(void)requestData{
    //请求检查项
    if(self.typeArray.count == 0){
        [RequestUtil withPOST:@"/common/dict/medicalReportTypeOption" parameters:@{@"data_type":self.data_type} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                self.typeArray = returnData;
                NSMutableArray *tempArray = [NSMutableArray array];
                for (NSInteger i=0; i<self.typeArray.count; i++) {
                    NSDictionary *tempDic = self.typeArray[i];
                    [tempArray addObject:LGNSString(tempDic[@"title"])];
                }
                [tempArray addObject:@"全部类型"];
                self.pickerArray = tempArray;
            }
        } error:^(NSError *error) {
            
        }];
    }
    //检验检查报告
    [RequestUtil withPOST:@"/doctor/Visitrecords/inspectionlist" parameters:@{@"report_struct_type":self.type,@"timeframe":self.year,@"patient_id":self.patientid,@"data_type":self.data_type} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if (code == 200) {
            self.dataArray = returnData;
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:LGErrorMessage offset:0];
        }
    }];
}

//选择类型、年份
-(void)selectButtonAction:(UIButton *)sender{
    if ((sender == self.typeButton && self.pickerArray.count == 0) || (sender == self.yearButton && self.yearArray.count == 0)) {
        [self requestData];
        return;
    }
    __block UIButton *button = sender;
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = (sender==self.typeButton)?@[self.pickerArray]:@[self.yearArray];
    pickerView.selectStr = (sender==self.typeButton)?self.typeStr:(self.year.length>0?self.year:@"全部时间");
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        NSString *result = LGNSString(resultArray[0]);
        if(button == self.typeButton){
            self.typeStr = result;
            NSString *type = @"";
            for (NSDictionary *tempDic in self.typeArray) {
                if([result isEqualToString:tempDic[@"title"]]){
                    type = LGNSString(tempDic[@"value"]);
                }
            }
            weakSelf.type = type;
            result = (result.length>8)?[NSString stringWithFormat:@"%@...",[result substringToIndex:6]]:result;
            [weakSelf.typeButton setTitle:result forState:UIControlStateNormal];
        }else{
            weakSelf.year = [result isEqualToString:@"全部时间"]?@"":result;
            NSString *title = [result isEqualToString:@"全部时间"]?@"全部时间":[NSString stringWithFormat:@"%@年",result];
            [weakSelf.yearButton setTitle:title forState:UIControlStateNormal];
        }
        [weakSelf requestData];
    };
}

-(void)checkPhotoWithPoint:(CGPoint)point index:(NSInteger)index photoArray:(NSArray *)array{
    self.checkPoint = point;
    LGCheckPhotoTool *photoView = [[LGCheckPhotoTool alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    photoView.picArray = array;
    [photoView showViewAnimation:point index:index];
    [[UIApplication sharedApplication].keyWindow addSubview:photoView];
}

//查看报告详情
/* 报废
-(void)checkReportDetail:(NSDictionary *)dataDic{
    NSString *type1 = LGNSString(dataDic[@"type"]);
    if([type1 isEqualToString:@"doctor"]){
        //自己添加的报告--查看报告详情
        [self editReportAction:dataDic];
        
    }else{
        //HIS
        NSString *type = LGNSString(dataDic[@"report_type"]);
        if([type isEqualToString:@"LR"]){
            //检验报告
            LGReportDetailLRController *controller = [[LGReportDetailLRController alloc]init];
            controller.recordId = LGNSString(dataDic[@"record_id"]);
            [self.navigationController pushViewController:controller animated:YES];
            
        }else if ([type isEqualToString:@"CT"]){
            //心脏彩超
        }else if ([type isEqualToString:@"MZ"]){
            //出院病情报告
        }else if ([type isEqualToString:@"BF"]){
            //门诊病历
        }else if ([type isEqualToString:@"CT_0001"]){
            //心电图1
            LGReportDetailCT01Controller *controller = [[LGReportDetailCT01Controller alloc]init];
            controller.recordId = LGNSString(dataDic[@"record_id"]);
            [self.navigationController pushViewController:controller animated:YES];
            
        }else if ([type isEqualToString:@"CT_0002"]){
            //超声心电图2
            LGReportDetailCT02Controller *controller = [[LGReportDetailCT02Controller alloc]init];
            controller.recordId = LGNSString(dataDic[@"record_id"]);
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

*/
 
//新增病历
-(void)addButtonAction{
    LGAddInspectReportController *controller = [[LGAddInspectReportController alloc]init];
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.addReportSuccess = ^{
        [weakSelf viewWillAppearAction];
    };
}

//编辑报告
-(void)editReportAction:(NSDictionary *)tempDic{
    //自己添加的报告--查看报告详情
    LGAddInspectReportController *controller = [[LGAddInspectReportController alloc]init];
    controller.patientid = self.patientid;
    controller.reportid = LGNSString(tempDic[@"record_id"]);
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.addReportSuccess = ^{
        [weakSelf viewWillAppearAction];
    };
}

//删除报告
-(void)deleteReportAction:(NSDictionary *)dataDic{
    NSString *content = [NSString stringWithFormat:@"即将删除%@项目检查报告，是否确认删除？",dataDic[@"exams_code_str"]];
    __block NSString *reportid = LGNSString(dataDic[@"record_id"]);
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:content sureAction:^{
        [RequestUtil withPOST:@"/doctor/Visitrecords/inspectionDel" parameters:@{@"record_id":reportid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [weakSelf requestData];
            }
        } error:^(NSError *error) {
            
        }];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *itemArray = self.dataArray[section][@"dlists"];
    return itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *itemArray = self.dataArray[indexPath.section][@"dlists"];
    LGInspectionReportCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(itemArray.count == 1){
        cell.type = @"single";
    }else if (indexPath.row == 0){
        cell.type = @"top";
    }else if (indexPath.row == itemArray.count-1){
        cell.type = @"bottom";
    }else{
        cell.type = @"middle";
    }
    cell.dataDic = itemArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.section][@"dlists"][indexPath.row];
    //查看报告详情
    LGInspectReportDetailController *controller = [[LGInspectReportDetailController alloc]init];
    controller.recordid = LGNSString(tempDic[@"record_id"]);
    controller.patientid = self.patientid;
    controller.data_type = self.data_type;
    controller.reportDate = LGNSString(tempDic[@"report_date"]);
    [self.navigationController pushViewController:controller animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(30);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGReportCenterHeaderView *headView = [[LGReportCenterHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(30))];
    headView.content = LGNSString(self.dataArray[section][@"datestr"]);
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}


#pragma mark
#pragma mark ====> 创建控件
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, viewPix(45), Screen_W, self.view.bounds.size.height-viewPix(45));
    self.emptyView.frame = CGRectMake(0, viewPix(45), Screen_W, self.view.bounds.size.height-viewPix(45));
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"YYYY";
    }
    return _formatter;
}

-(UIView *)topLine{
    if(!_topLine){
        _topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 1)];
        _topLine.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
    }
    return _topLine;
}

-(UIButton *)typeButton{
    if(!_typeButton){
        _typeButton = [UIButton buttonWithTitle:@"全部类型" titleFont:LGFont(14) textColor:@"#282828" imageName:@""];
        [_typeButton setShadoWithColor:@"#99B6D7" offset:CGSizeMake(0, 2) opacity:0.15 radius:8];
        _typeButton.frame = CGRectMake(viewPix(16), viewPix(5), (Screen_W-viewPix(44))/2.0, viewPix(34));
        _typeButton.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, viewPix(35));
        _typeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _typeButton.backgroundColor = [UIColor whiteColor];
        [_typeButton addTarget:self action:@selector(selectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UIImageView *tipView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blackTipDown16"]];
        [_typeButton addSubview:tipView];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.typeButton).offset(-viewPix(12));
            make.centerY.equalTo(self.typeButton);
            make.width.height.equalTo(@(viewPix(16)));
        }];
    }
    return _typeButton;
}

-(UIButton *)yearButton{
    if(!_yearButton){
        _yearButton = [UIButton buttonWithTitle:@"全部时间" titleFont:LGFont(14) textColor:@"#282828" imageName:@""];
        [_yearButton setShadoWithColor:@"#99B6D7" offset:CGSizeMake(0, 2) opacity:0.15 radius:8];
        _yearButton.frame = CGRectMake(kMaxX(self.typeButton.frame)+viewPix(12), viewPix(5), (Screen_W-viewPix(44))/2.0, viewPix(34));
        _yearButton.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, viewPix(35));
        _yearButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _yearButton.backgroundColor = [UIColor whiteColor];
        [_yearButton addTarget:self action:@selector(selectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UIImageView *tipView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blackTipDown16"]];
        [_yearButton addSubview:tipView];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.yearButton).offset(-viewPix(12));
            make.centerY.equalTo(self.yearButton);
            make.width.height.equalTo(@(viewPix(16)));
        }];
    }
    return _yearButton;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewPix(45), Screen_W, Screen_H-topBarHeight-viewPix(89)) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGInspectionReportCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = viewPix(46);
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(UIButton *)addButton{
    if(!_addButton){
        _addButton = [UIButton buttonWithTitle:@"新增报告" topMargin:kMaxY(self.tableView.frame)+viewPix(5)];
        [_addButton addTarget:self action:@selector(addButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}


@end
